package com.itfreer.ui.advanced;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.itfreer.ui.R;
import com.itfreer.ui.advanced.base.PageFragmentAdapter;

import java.util.List;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;

/**
 * 定义图标和文字的TabPage控件
 */
public class TabPageView extends LinearLayout implements ViewPager.OnPageChangeListener {

    /**
     * 空标题对象
     */
    private static final CharSequence EMPTY_TITLE = "";

    /**
     * tab选择器
     */
    private Runnable mTabSelector;

    /**
     * tab导航容器ViewPager
     */
    private LinearLayout mTabLayout;

    /**
     * tab内容容器LinearLayout
     */
    private ScrollViewPager mViewPager;

    /**
     * 当前选择的tab索引
     */
    private int mSelectedTabIndex;

    /**
     * tab的宽度
     */
    private int mTabWidth;

    /**
     * Fragment列表
     */
    private PageFragmentAdapter viewAdapter;
    /**
     * view的名称
     */
    private List<String> viewNames;
    /**
     * view的ICON
     */
    private List<Integer> viewIcons;

    /**
     * 设置是否可滑动切换
     * @return
     */
    private boolean canScroll = true;

    /**
     * 设置是否可滑动切换
     * @return
     */
    public boolean getCanScroll(){
        return canScroll;
    }

    /**
     * 获取是否可滑动切换
     * @param canScroll
     */
    public void setCanScroll(boolean canScroll){
        this.canScroll = canScroll;
        mViewPager.setCanScroll(canScroll);
    }

    /**
     * 初始化
     * @param context
     */
    public TabPageView(Context context) {
        this(context, null);
    }

    /**
     * 初始化
     * @param context
     * @param attrs
     */
    public TabPageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setHorizontalScrollBarEnabled(false);
        View view = View.inflate(context, R.layout.com_itfreer_core_ui_advanced_tabpageview, null);
        addView(view);

        mViewPager = (ScrollViewPager)findViewById(R.id.com_itfreer_core_ui_advanced_tabpageview_viewpager);
        mViewPager.setCanScroll(canScroll);
        mTabLayout = (LinearLayout)findViewById(R.id.com_itfreer_core_ui_advanced_tabpageview_viewtab);
    }

    /**
     * 初始化
     * @param viewAdapter
     * @param viewNames
     * @param viewIcons
     */
    public void initViews(PageFragmentAdapter viewAdapter,
                           List<String> viewNames, List<Integer> viewIcons) {
        this.viewAdapter = viewAdapter;
        this.viewNames = viewNames;
        this.viewIcons = viewIcons;

        mViewPager.setAdapter(viewAdapter);
        mViewPager.setOnPageChangeListener(this);
        notifyDataSetChanged();
    }

    /**
     * 通知数据改变
     */
    protected void notifyDataSetChanged() {
        mTabLayout.removeAllViews();

        if(viewAdapter!=null && viewAdapter.getCount()>0){
            final int count = viewAdapter.getCount();
            for (int i = 0; i < count; i++) {
                CharSequence title = viewNames.get(i);
                if (title == null) {
                    title = EMPTY_TITLE;
                }
                int iconResId = viewIcons.get(i);
                addTab(i, title, iconResId);
            }
            if (mSelectedTabIndex > count) {
                mSelectedTabIndex = count - 1;
            }
            setCurrentItem(mSelectedTabIndex);
        }
        requestLayout();
    }

    /**
     * 添加tab项
     * @param index
     * @param text
     * @param iconResId
     */
    private void addTab(int index, CharSequence text, int iconResId) {
        final TabView tabView = new TabView(getContext());
        tabView.mIndex = index;
        tabView.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                TabView tabView = (TabView) view;
                final int newSelected = tabView.getIndex();
                mViewPager.setCurrentItem(newSelected);
            }
        });
        tabView.setText(text);
        if (iconResId > 0) {
            tabView.setIcon(iconResId);
        }
        mTabLayout.addView(tabView, new LayoutParams(0, MATCH_PARENT, 1));
    }

    /**
     * 保离当前的选择状态
     */
    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (mTabSelector != null) {
            // Re-post the selector we saved
            post(mTabSelector);
        }
    }

    /**
     * 保离当前的选择状态
     */
    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mTabSelector != null) {
            removeCallbacks(mTabSelector);
        }
    }

    /**
     * ViewPager事件
     * @param arg0
     */
    @Override
    public void onPageScrollStateChanged(int arg0) {

    }

    /**
     * ViewPager事件
     * @param arg0
     */
    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {

    }

    /**
     * ViewPager事件
     * @param arg0
     */
    @Override
    public void onPageSelected(int arg0) {
        setCurrentItem(arg0);
    }

    /**
     * 设置当前项
     * @param item
     */
    public void setCurrentItem(int item) {
        if (mViewPager == null) {
            throw new IllegalStateException("ViewPager has not been bound.");
        }
        mSelectedTabIndex = item;
        mViewPager.setCurrentItem(item);

        final int tabCount = mTabLayout.getChildCount();
        for (int i = 0; i < tabCount; i++) {
            final View child = mTabLayout.getChildAt(i);
            final boolean isSelected = (i == item);
            child.setSelected(isSelected);
            if (isSelected) {
                animateToTab(item);
            }
        }
    }

    /**
     * 保存选择状态
     * @param position
     */
    private void animateToTab(final int position) {
        final View tabView = mTabLayout.getChildAt(position);
        if (mTabSelector != null) {
            removeCallbacks(mTabSelector);
        }
        mTabSelector = new Runnable() {
            public void run() {
                final int scrollPos = tabView.getLeft() - (getWidth() - tabView.getWidth()) / 2;
                mTabSelector = null;
            }
        };
        post(mTabSelector);
    }

    /**
     * 定义Tab按钮
     */
    private class TabView extends LinearLayout {
        private int mIndex;
        private ImageView mImageView;
        private TextView mTextView;

        public TabView(Context context) {
            super(context, null, R.attr.tabView);
            View view = View.inflate(context, R.layout.com_itfreer_core_ui_advanced_tabpageview_tab, null);
            mImageView = (ImageView) view.findViewById(R.id.com_itfreer_core_ui_advanced_tabpageview_tab_image);
            mTextView = (TextView) view.findViewById(R.id.com_itfreer_core_ui_advanced_tabpageview_tab_text);
            this.addView(view);
        }

        @Override
        public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);

            // Re-measure if we went beyond our maximum size.
            if (mTabWidth > 0) {
                super.onMeasure(MeasureSpec.makeMeasureSpec(mTabWidth, MeasureSpec.EXACTLY),
                        heightMeasureSpec);
            }
        }

        public void setText(CharSequence text) {
            mTextView.setText(text);
        }

        public void setIcon(int resId) {
            if (resId > 0) {
                mImageView.setImageResource(resId);
            }
        }

        public int getIndex() {
            return mIndex;
        }
    }
}
